package com.railway.app;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.railway.classes.Ticket;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
 *
 * @author Moofie
 */
public class SeatAmendDialog extends javax.swing.JDialog {
    //public Ticket ticket = new Ticket();
    private int aCount = 0;
    public static String[] tickets = new String[56];
    private String[] bookedSeat = new String[56];
    JToggleButton[] jtbSeat = new JToggleButton[56];
    JFrame ticketAmendPanel;
    

    /**
     * Creates new form SeatDialog
     */
    public SeatAmendDialog(java.awt.Frame parent, boolean modal, JFrame frame) {
        super(parent, modal);
        initComponents();
        setSampleButton();
        initializeSelectCoachTable();
        this.ticketAmendPanel = frame;
        jbtAmend.setEnabled(true);
        
    }

    private void setSampleButton(){
        jtbSampleAvailable.setBackground(Color.pink);
        jtbSampleBooked.setEnabled(false);
    }
    
    
    
     
    private void initializeSelectCoachTable(){
        aCount=0;
        jpSeat.removeAll();
        aCount=0;
        String shid = Ticket.getShid();
        String dates = Ticket.getBookedDate();
        String coach = "A";
        String a = RestServer.httpGet("coachMap", jcbCoach.getSelectedItem().toString());
        String b = RestServer.httpGet("coachMapBooked", coach+"/"+shid+"/"+dates);
        System.out.println(a);
        System.out.println(b);
        try {
            JSONObject json = new JSONObject(a);
            JSONArray content = json.getJSONArray("content");
            JSONObject jsonb = new JSONObject(b);
            JSONArray contentB = jsonb.getJSONArray("content");

            int length = content.length();
            int y = 0;
            GridLayout layout = new GridLayout(14,4);
                layout.setHgap(10);
                layout.setVgap(3);
            jpSeat.setLayout(layout);

            for(int k = 0 ; k < contentB.length() ; k++){
                bookedSeat[k] = contentB.getJSONObject(k).getString("seatid");
                System.out.println(bookedSeat[k]);
            }

            for(int i = 0 ; i < 56 ; i++){
                if(content.getJSONObject(i).getString("seatid").equals(bookedSeat[y])){
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jpSeat.add(jtbSeat[i]);
                    jtbSeat[i].setEnabled(false);
                    y++;
                }else{
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jtbSeat[i].setBackground(Color.pink);
                    jtbSeat[i].setEnabled(true);
                    jpSeat.add(jtbSeat[i]);
                
                
                jtbSeat[i].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e){
                        JToggleButton jtb = (JToggleButton) e.getSource();
                        if(jtb.isSelected()){
                            if(aCount>0){
                                Toast.makeText(getParent(), "Can select only one seat", Toast.LENGTH_LONG).display();
                                jtb.setSelected(false);
                            }else{
                                jtb.setBackground(Color.green);
                                aCount++;
                            }
                            
                        }else{
                            jtb.setBackground(Color.pink);
                            aCount--;
                        }
                    }
                });
            }
            }
            this.pack();
            jpSeat.setVisible(true);
            jpSeat.revalidate();
            jpSeat.repaint();

        } catch (JSONException ex) {
            JOptionPane.showMessageDialog(null,"Error: "+ex);
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpMainSeat = new javax.swing.JPanel();
        jcbCoach = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jpSeat = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jtbSampleBooked = new javax.swing.JButton();
        jtbSampleAvailable = new javax.swing.JButton();
        jbtBack = new javax.swing.JButton();
        jbtAmend = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);

        jpMainSeat.setBackground(new java.awt.Color(46, 204, 113));
        jpMainSeat.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 51), 2));
        jpMainSeat.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jpMainSeat.setMaximumSize(new java.awt.Dimension(870, 440));
        jpMainSeat.setMinimumSize(new java.awt.Dimension(870, 440));
        jpMainSeat.setName(""); // NOI18N
        jpMainSeat.setPreferredSize(new java.awt.Dimension(870, 440));
        jpMainSeat.setRequestFocusEnabled(false);

        jcbCoach.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A", "B", "C", "D", "E", "F" }));
        jcbCoach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbCoachActionPerformed(evt);
            }
        });

        jLabel1.setText("Coach");

        javax.swing.GroupLayout jpSeatLayout = new javax.swing.GroupLayout(jpSeat);
        jpSeat.setLayout(jpSeatLayout);
        jpSeatLayout.setHorizontalGroup(
            jpSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 376, Short.MAX_VALUE)
        );
        jpSeatLayout.setVerticalGroup(
            jpSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 405, Short.MAX_VALUE)
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jtbSampleBooked.setText("Booked");

        jtbSampleAvailable.setText("Available");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jtbSampleAvailable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtbSampleBooked, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jtbSampleAvailable)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jtbSampleBooked)
                .addContainerGap(53, Short.MAX_VALUE))
        );

        jbtBack.setText("Back");
        jbtBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtBackActionPerformed(evt);
            }
        });

        jbtAmend.setText("Amend");
        jbtAmend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAmendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpMainSeatLayout = new javax.swing.GroupLayout(jpMainSeat);
        jpMainSeat.setLayout(jpMainSeatLayout);
        jpMainSeatLayout.setHorizontalGroup(
            jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpMainSeatLayout.createSequentialGroup()
                .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpMainSeatLayout.createSequentialGroup()
                        .addGap(230, 230, 230)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbCoach, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpMainSeatLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jpSeat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpMainSeatLayout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jpMainSeatLayout.createSequentialGroup()
                                .addGap(27, 27, 27)
                                .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jbtBack, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtAmend, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpMainSeatLayout.setVerticalGroup(
            jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpMainSeatLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcbCoach, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpMainSeatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpSeat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jpMainSeatLayout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(136, 136, 136)
                        .addComponent(jbtBack, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jbtAmend, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(7, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 574, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpMainSeat, javax.swing.GroupLayout.PREFERRED_SIZE, 554, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 480, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpMainSeat, javax.swing.GroupLayout.PREFERRED_SIZE, 458, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jcbCoachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbCoachActionPerformed
        //System.out.println(ctmModel.getRowCount());
        aCount=0;
        jpSeat.removeAll();
        String shid = Ticket.getShid();
        String dates = Ticket.getBookedDate();
        String coach = jcbCoach.getSelectedItem().toString();
        String a = RestServer.httpGet("coachMap", jcbCoach.getSelectedItem().toString());
        String b = RestServer.httpGet("coachMapBooked", coach+"/"+shid+"/"+dates);
        System.out.println(a);
        System.out.println(b);
        try {
            JSONObject json = new JSONObject(a);
            JSONArray content = json.getJSONArray("content");
            JSONObject jsonb = new JSONObject(b);
            JSONArray contentB = jsonb.getJSONArray("content");

            int length = content.length();
            int y = 0;
            GridLayout layout = new GridLayout(14,4);
            layout.setHgap(10);
            layout.setVgap(3);
            jpSeat.setLayout(layout);

            for(int k = 0 ; k < contentB.length() ; k++){
                bookedSeat[k] = contentB.getJSONObject(k).getString("seatid");
                System.out.println(bookedSeat[k]);
            }

            for(int i = 0 ; i < 56 ; i++){
                if(content.getJSONObject(i).getString("seatid").equals(bookedSeat[y])){
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jpSeat.add(jtbSeat[i]);
                    jtbSeat[i].setEnabled(false);
                    y++;
                }else{
                    jtbSeat[i] = new JToggleButton(""+content.getJSONObject(i).getString("seatid")+"->"+content.getJSONObject(i).getString("seatNo"));
                    jtbSeat[i].setBackground(Color.pink);
                    jtbSeat[i].setEnabled(true);
                    jpSeat.add(jtbSeat[i]);

                    jtbSeat[i].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                            JToggleButton jtb = (JToggleButton) e.getSource();
                            if(jtb.isSelected()){
                                if(aCount>0){
                                    Toast.makeText(getParent(), "Can select only one seat", Toast.LENGTH_LONG).display();
                                    jtb.setSelected(false);
                                }else{
                                    jtb.setBackground(Color.green);
                                    aCount++;
                                    
                                }
                            }else{
                                jtb.setBackground(Color.pink);
                                aCount--;
                            }
                        }
                    });
                }
            }
            this.pack();
            jpSeat.setVisible(true);
            jpSeat.revalidate();
            jpSeat.repaint();

        } catch (JSONException ex) {
            JOptionPane.showMessageDialog(null,"Error: "+ex);
        }
    }//GEN-LAST:event_jcbCoachActionPerformed

    private void jbtBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBackActionPerformed
        this.dispose();
    }//GEN-LAST:event_jbtBackActionPerformed

    private void jbtAmendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAmendActionPerformed
        String seatNo;
        String fare = null;
        String[] aSplit;
        for(int i = 0; i < 56; i++){
            if(jtbSeat[i].isSelected()){
                aSplit = jtbSeat[i].getActionCommand().split("->");
                Ticket.setSeatNo(aSplit[0]);
            }
        }
        
        String fareTicket = RestServer.httpGet("ticketGetOldFare",Ticket.getReferenceNo());
        try{
            JSONObject jsonTicket = new JSONObject(fareTicket);
            int statusFare = jsonTicket.getInt("status");
            if(statusFare == 200){
                
            }else{
                System.out.println("Fare not able to initialize");
            }
        }catch(JSONException ex){
            System.out.println(ex);
        }
        Map<String, Object> dataAmendBookedSeat = new HashMap<>();
        dataAmendBookedSeat.put("shid",Ticket.getShid());
        dataAmendBookedSeat.put("status", "AMD");
        dataAmendBookedSeat.put("bookedDate", Ticket.getBookedDate());
        dataAmendBookedSeat.put("seatid",Ticket.getSeatNo());
        dataAmendBookedSeat.put("referenceNo",Ticket.getReferenceNo());
        
        Map<String, Object> dataAmendTicket = new HashMap<>();
        dataAmendTicket.put("shid",Ticket.getShid());
        dataAmendTicket.put("status", "AMD");
        dataAmendTicket.put("departureDate", Ticket.getBookedDate());
        dataAmendTicket.put("class", Ticket.getClasses());
        dataAmendTicket.put("departure",Ticket.getDepatureTime());
        dataAmendTicket.put("referenceNo",Ticket.getReferenceNo());
        dataAmendTicket.put("arrival", "00:00:00");
        dataAmendTicket.put("origin", Ticket.getOrigin());
        dataAmendTicket.put("destination", Ticket.getDestination());
        dataAmendTicket.put("fare", "33.00");
        
        System.out.println(Ticket.getBookedDate());
        System.out.println(Ticket.getOrigin());
        System.out.println(Ticket.getDestination());
        System.out.println(fare);
                 
                        
        
        String amendBookedSeat = RestServer.httpPost("amendBookedSeat", dataAmendBookedSeat);
        String amendTicket = RestServer.httpPost("amendTicket", dataAmendTicket);
        
        System.out.println(amendTicket);
        System.out.println(amendBookedSeat);
        try {
            JSONObject jsonAmendBookedSeat = new JSONObject(amendBookedSeat);
            JSONObject jsonAmendTicket = new JSONObject(amendTicket);
            
            System.out.println(jsonAmendBookedSeat.get("status"));
            System.out.println(jsonAmendTicket.get("status"));
            
            int statusBook = jsonAmendBookedSeat.getInt("status");
            int statusTicket = jsonAmendTicket.getInt("status");

            if( statusBook==200 && statusTicket==200){
                Toast.makeText(getParent(), "Amend successfully", Toast.LENGTH_LONG).display();
                jbtAmend.setEnabled(false);
                initializeSelectCoachTable();
                AmendTicketPrint atp = new AmendTicketPrint(null,true,this,null);
                atp.show();
            }
        } catch (JSONException ex) {
            System.out.println(ex);
        }
        
        
        
        
       
        
    }//GEN-LAST:event_jbtAmendActionPerformed




    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbtAmend;
    private javax.swing.JButton jbtBack;
    private javax.swing.JComboBox jcbCoach;
    private javax.swing.JPanel jpMainSeat;
    private javax.swing.JPanel jpSeat;
    private javax.swing.JButton jtbSampleAvailable;
    private javax.swing.JButton jtbSampleBooked;
    // End of variables declaration//GEN-END:variables
}
